﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using APMS.WebSite.Common;
using APMS.WebSite.Models.DataStore;
using APMS.WebSite.Models.ViewData.Pages;
using APMS.WebSite.Models.ViewData.UserControls;

namespace APMS.WebSite.Controllers
{
    /// <summary>
    /// MessageController controls all Views related to Message operation which are:
    /// * Index (/InProject/{projectId}/Message/)
    /// * List (/InProject/{projectId}/Message/List)
    /// * Create (/InProject/{projectId}/Message/Create)
    /// * Update (/InProject/{projectId}/Message/Update/{id})
    /// * View (/InProject/{projectId}/Message/View/{id})
    /// * Delete (/InProject/{projectId}/Message/Delete/{id})
    /// * Add Comment (/InProject/{projectId}/Message/AddComment/{id})
    /// * MORE
    /// </summary>
    /// <version>$Revision$ $Date$</version>
    /// <history>
    /// <record>09/15/2008. raQuiam - Created this file</record>
    /// </history>
    [HandleError]
    public class MessageController : ProjectBaseController
    {
        #region Keys for ViewData
        /// <summary>
        /// Use in method List
        /// </summary>
        public const string ALL_MESSAGES = "AllMessages";
        #endregion

        #region List Action
        /// <summary>
        /// List all message under target project 
        /// </summary>
        /// <returns></returns>
        public ActionResult List(int projectId)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.Message);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);

            // Set Window Title
            base.SetTitle(currentProject.ProjectName + " | All Messages", true);
            base.SetInfoToUserControls(currentProject);

            // Query all message under current project
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from message in db.Message
                where
                    message.ProjectID == currentProject.ProjectID
                orderby message.ModifyDate descending
                select message;

            ViewData[CURRENT_PROJECT] = currentProject;
            ViewData[ALL_MESSAGES] = query.ToList();

            return View("List");
        }
        #endregion

        #region Create Action
        /// <summary>
        /// Create new Message
        /// </summary>
        /// <returns></returns>
        public ActionResult Create(int projectId)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.Message);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);

            // Set Window Title
            base.SetTitle(currentProject.ProjectName + " | Create New Message", true);
            base.SetInfoToUserControls(currentProject);

            // Prepare ViewData
            ManageMessageViewData viewData = new ManageMessageViewData();
            viewData.CurrentProject = currentProject;

            // If POST means UPDATE the value from Request.Form to DB
            // If GET means VIEW the value from DB
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                string msgTopic = Request.Form["messageTopic"];
                string msgDetail = Request.Form["messageDetails"];
                #endregion

                // Prepare to INSERT by Linq
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();

                Message newMessage = new Message();
                newMessage.ProjectID = projectId;
                newMessage.MessageTopic = msgTopic;
                newMessage.MessageDetail = msgDetail;
                newMessage.UserName = UserProfile.UserName;
                newMessage.ModifyDate = DateTime.Now;
                newMessage.AddDate = DateTime.Now;

                db.Message.InsertOnSubmit(newMessage);
                db.SubmitChanges();

                // Fill the rest of viewData
                viewData.CurrentMessage = newMessage;
                viewData.IsCurrentMessageUpdate = true;

                // Redirect to  Project Overview
                return RedirectToAction("List", new { projectId = projectId });
                #endregion
            }
            else
            {
                viewData.IsCurrentMessageUpdate = false;
            }

            return View("Create", viewData);
        }
        #endregion

        #region View/Update Actions
        public ActionResult View(int projectId, int id)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.Message);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);
            base.SetInfoToUserControls(currentProject);

            // Prepare ViewData
            ManageMessageViewData viewData = new ManageMessageViewData();
            viewData.CurrentProject = currentProject;

            // If GET means VIEW the value from DB
            // Support only GET
            if (Request.HttpMethod == Constants.HttpMethod.GET)
            {
                // Query specify message under current project
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
                var query =
                    from message in db.Message
                    where
                        message.ProjectID == currentProject.ProjectID &&
                        message.MessageID == id
                    orderby message.ModifyDate descending
                    select message;

                //Query 2
                var query2 =
                    from comment in db.Comment
                    where
                        comment.MessageID == id
                    orderby comment.ModifyDate descending
                    select comment;

                // Make sure the target message is still existed
                if (query.Count() > 0)
                {
                    viewData.CurrentMessage = query.First();
                    viewData.Comments = query2.ToList();

                    // Set Window Title
                    base.SetTitle(currentProject.ProjectName + " | " + viewData.CurrentMessage.MessageTopic, true);
                }
                else
                {
                    throw new ApplicationException("Target Message is no longer existed");
                }

                viewData.IsCurrentMessageUpdate = false;
            }

            return View("View", viewData);
        }

        public ActionResult Update(int projectId, int id)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.Message);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);

            // Set Window Title
            base.SetTitle(currentProject.ProjectName + " | Create New Message", true);
            base.SetInfoToUserControls(currentProject);

            // Prepare ViewData
            ManageMessageViewData viewData = new ManageMessageViewData();
            viewData.CurrentProject = currentProject;

            // Query specify message under current project
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from message in db.Message
                where
                    message.ProjectID == currentProject.ProjectID &&
                    message.MessageID == id
                orderby message.ModifyDate descending
                select message;

            // Make sure the target message is still existed
            if (query.Count() > 0)
            {
                // Read value from DB
                viewData.CurrentMessage = query.First();

                // If POST means UPDATE the value from Request.Form to DB
                // If GET means VIEW the value from DB
                if (Request.HttpMethod == Constants.HttpMethod.POST)
                {
                    #region Create new record in DB

                    #region Extract values from Form
                    string msgTopic = Request.Form["messageTopic"];
                    string msgDetail = Request.Form["messageDetails"];
                    #endregion

                    // Update value to DB
                    viewData.CurrentMessage.MessageTopic = msgTopic;
                    viewData.CurrentMessage.MessageDetail = msgDetail;
                    viewData.CurrentMessage.ModifyDate = DateTime.Now;

                    viewData.IsCurrentMessageUpdate = true;

                    db.SubmitChanges();

                    // Redirect to  View Message
                    return RedirectToAction("View", new { projectId = projectId, id = viewData.CurrentMessage.MessageID });

                    #endregion
                }
                else
                {
                    viewData.IsCurrentMessageUpdate = false;
                }
            }
            else
            {
                throw new ApplicationException("Message is no longer existed");
            }

            return View("Update", viewData);
        }
        #endregion

        #region Delete Action
        /// <summary>
        /// Delete message
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int projectId, int id)
        {
            // Query specify message under current project
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from message in db.Message
                where
                    message.ProjectID == projectId &&
                    message.MessageID == id
                orderby message.ModifyDate descending
                select message;

            // Make sure the target message is still existed
            if (query.Count() > 0)
            {
                // Read value from DB
                Message currentMessage = query.First();

                db.Message.DeleteOnSubmit(currentMessage);
                db.SubmitChanges();
            }
            else
            {
                throw new ApplicationException("Message is no longer existed");
            }

            // Redirect to  List Messages
            return RedirectToAction("List", new { projectId = projectId });
        }
        #endregion

        #region Add Comment
        public ActionResult AddComment(int projectId, int id)
        {
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                string commentDetails = Request.Form["commentDetails"];
                #endregion

                // Prepare to INSERT by Linq
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();

                Comment newComment = new Comment();
                newComment.MessageID = id;
                newComment.UserName = UserProfile.UserName;
                newComment.CommentDetail = commentDetails;
                newComment.AddDate = DateTime.Now;
                newComment.ModifyDate = DateTime.Now;

                db.Comment.InsertOnSubmit(newComment);
                db.SubmitChanges();
                #endregion
            }

            // Redirect to  Project Overview
            return RedirectToAction("View", new { projectId = projectId, id = id });
        }
        #endregion

        #region Delete Comment
        public ActionResult DeleteComment(int projectId, int id)
        {
            // Redirect to  Project Overview
            return RedirectToAction("View", new { projectId = projectId, id = id });

            //// Query specify message under current project
            //MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            //var query =
            //    from comment in db.Comment
            //    where
            //        comment.MessageID == id
            //    orderby message.ModifyDate descending
            //    select message;

            //// Make sure the target message is still existed
            //if (query.Count() > 0)
            //{
            //    // Read value from DB
            //    Message currentMessage = query.First();

            //    db.Message.DeleteOnSubmit(currentMessage);
            //    db.SubmitChanges();
            //}
            //else
            //{
            //    throw new ApplicationException("Message is no longer existed");
            //}

            //// Redirect to  List Messages
            //return RedirectToAction("List", new { projectId = projectId });
        }
        #endregion
    }
}
